<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\api\controller;
use think\Db;

class Datas extends Base
{
    protected $config = array(
        1 => [1,2,3,2,3,'end'],//
        2 => [1,2,3,2,3,2,3,'end'],//
        3 => [1,4,1,4,1,2,3,'end'],//
        4 => [1,4,1,2,3,'end'],//
        );
    /**
     * 获取用户定位数据
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function getUserLocation(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $data = array();
        $data['mm_user_id'] = $user_id;
        $data['mm_match_id'] = $m_id;
        $match = Db::table('up_match_now')
            ->where('mn_m_id',$m_id)
            ->where('mn_end_time','2000-12-12 12:12:12')
            ->find();
        if($match){
            $users = Db::table('up_match_apply_info')
                ->where('ma_match_id',$m_id)
                ->where('ma_group',$match['mn_g_id'])
                ->where('ma_apply_status',2)
                ->where('ma_role',1)
                ->where('ma_user_id',$user_id)
                ->field('ma_role,ma_id')
                ->find();
            if($users){
                $data['mm_mg_id'] = $match['mn_g_id'];
                $data['mm_ml_id'] = $match['mn_l_id'];
                $have = Db::table('up_match_datas')
                    ->where('mm_match_id',$m_id)
                    ->where('mm_mg_id',$match['mn_g_id'])
                    ->where('mm_ml_id',$match['mn_l_id'])
                    ->where('mm_user_id',$user_id)
                    ->order('mm_time desc')
                    ->field('max(mm_biao) biao,max(mm_times) times,mm_lat,mm_lon')
                    ->find();
                if($have){
                    $data['mm_biao'] = $have['biao'];
                    $data['mm_times'] = $have['times'];
                    $data['mm_speed'] = $this->getDistance($have['mm_lat'],$have['mm_lon'],$lat,$lon);
                }
            }
        }
        $data['mm_lat'] = $lat;
        $data['mm_lon'] = $lon;
        $data['mm_time'] = $time;
        $image_s = Db::table('up_match_apply_info')->alias('ai')
            ->join('up_club c','ai.ma_club_id=c.club_id','left')
            ->where('ma_match_id',$m_id)
            ->where('ma_apply_status',2)
            ->where('ma_user_id',$user_id)
            ->field('club_image,ma_fan_code,ma_boat_code')
            ->find();
        if($image_s){
            $data['mm_fan'] = $image_s['ma_fan_code'];
            $data['mm_name'] = $image_s['ma_boat_code'];
            $data['mm_image'] = $image_s['club_image'];
        }
        Db::table('up_match_datas')->insert($data);
        return  json(array('status'=>200,'msg'=>'ok'));
    }
    /**
     * 用户取数据（船员和船长都从这拿数据）
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function getUserData(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $match = Db::table('up_match_now')
            ->where('mn_m_id',$m_id)
            ->where('mn_end_time','2000-12-12 12:12:12')
            ->find();
        if($match){
            $chaminutes = strtotime($time) - strtotime($match['mn_begin_time']);
            $cha = $chaminutes / 60;//是不是超过5分钟了
            $match['minutes'] = 300 - $chaminutes;
            if($chaminutes >= 300){
                $match['minutes'] = $chaminutes - 300;
            }
            $user = Db::table('up_match_apply_info')
                ->where('ma_match_id',$m_id)
                ->where('ma_group',$match['mn_g_id'])
                ->where('ma_apply_status',2)
                ->where('ma_user_id',$user_id)
                ->field('ma_role,ma_id,ma_real_pay_user_id')
                ->find();
            $match['top'] = '-';
            $match['speed'] = '-';
            $match['top_m'] = '-';
            $match['upone_m'] = '-';
            $match['start_m'] = '-';
            if($user && $cha > 5){ //只有你在里面在比赛了，而且超过5分钟了，说明你有数据了，就可以计算了
                $subQuery = Db::table('up_match_datas')
                    ->where('mm_match_id',$m_id)
                    ->where('mm_mg_id',$match['mn_g_id'])
                    ->where('mm_ml_id',$match['mn_l_id'])
                    ->order('mm_time desc')
                    ->buildSql();
                $reldata = Db::table($subQuery."a")
//                    ->field("a.mm_lat,a.mm_lon,a.mm_user_id,a.mm_match_id,a.mm_mg_id,a.mm_ml_id")
                    ->group('mm_user_id')
                    ->order('mm_time desc')
                    ->select();
                $have = Db::table('up_match_ls_res')
                    ->where('ls_m_id',$m_id)
                    ->where('ls_mg_id',$match['mn_g_id'])
                    ->where('ls_ml_id',$match['mn_l_id'])
                    ->order('ls_time asc')
                    ->column('ls_user_id');
                if(count($have) < count($reldata)){ //结算成绩的数量要小于参加比赛的队伍的数量
                    if(in_array($user['ma_real_pay_user_id'],$have)){ //说明这支队伍已经提交比赛了
                        $match['top'] = array_search($user['ma_real_pay_user_id'],$have) + 1;
                    }else{
                        $scores = [];
                        foreach ($reldata as $k=>$v){
                            $distance = $this->getDistance($v['mm_lat'],$v['mm_lon'],$match['mn_lat_' . $v['mm_biao']],$match['mn_lon_' . $v['mm_biao']]);
                            $v['distance'] = $distance;
                            $scores[] = $v;
                            if($v['mm_user_id'] == $user['ma_real_pay_user_id']){
                                $match['speed'] = $v['mm_speed'];
                            }
                        }

//                        先按照距离正序排，再按照等级倒序排
                        $scores = arrayToSort($scores,'distance',"SORT_ASC");
                        $scores = arrayToSort($scores,'mm_times',"SORT_DESC");
                        $my_k = array_search($user['ma_real_pay_user_id'],$scores);
                        $match['top'] = count($have) + $my_k + 1;
                        if($my_k > 0){
                            $match['top_m'] = $scores[$my_k]['distance'] - $scores[0]['distance'];
                            $match['upone_m'] = $scores[$my_k]['distance'] - $scores[$my_k-1]['distance'];
                            $match['start_m'] = $this->getDistance($scores[$my_k]['mm_lat'],$scores[$my_k]['mm_lon'],$match['mn_lat_' . $scores[$my_k]['mm_biao']],$match['mn_lon_' . $scores[$my_k]['mm_biao']]);
                        }
                        if($scores[$my_k]['distance'] <= 1){ //我跑完了
                            //1、改次数和下一个标，再判断要不要入结果库(改标和次数的时候不能用id改，就得这么改，一改全改)
                            $all_line = $this->config[$match['mn_msi_id']];
                            Db::table('up_match_datas')
                                ->where('mm_match_id',$m_id)
                                ->where('mm_mg_id',$match['mn_g_id'])
                                ->where('mm_ml_id',$match['mn_l_id'])
                                ->where('mm_user_id',$scores[$my_k]['mm_user_id'])
                                ->setInc('mm_times',1);
                            if($scores[$my_k]['mm_times']+1 >= count($all_line)){ // 跑完了，入
                                $insertres = [
                                    'ls_m_id' => $m_id ,
                                    'ls_mg_id' => $match['mn_g_id'] ,
                                    'ls_ml_id' => $match['mn_l_id'] ,
                                    'ls_user_id' => $scores[$my_k]['mm_user_id'] ,
                                    'ls_score' => $match['top'] ,
                                    'ls_time' => $time
                                ];
                                Db::table('up_match_ls_res')->insert($insertres);
                            }else{
                                Db::table('up_match_datas')
                                    ->where('mm_match_id',$m_id)
                                    ->where('mm_mg_id',$match['mn_g_id'])
                                    ->where('mm_ml_id',$match['mn_l_id'])
                                    ->where('mm_user_id',$scores[$my_k]['mm_user_id'])
                                    ->setField('mm_biao',$all_line[$scores[$my_k]['mm_times']+1]);
                            }
                        }
                    }
                }
            }
        }else{
            $have = Db::table('up_match_choose')->where('mn_m_id',$m_id)->find();
            if($have){
                $match = $have;
            }else{
                $match = [];
            }
            $match['top'] = '-';
            $match['speed'] = '-';
            $match['top_m'] = '-';
            $match['upone_m'] = '-';
            $match['start_m'] = '-';
            $match['minutes'] = 0;
        }
        return  json(array('status'=>200,'msg'=>$match));
    }
    /**
     * 开始比赛
     * 参数：
     * $m_id，$g_id，$l_id，$msi_id，$sf_id，$fs_id
     * $start，$one，$two，$three，$four，$end
     * @return string
     */
    public function startMatch(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        if(!isset($one) || empty($one)){ $one = 0; }
        if(!isset($two) || empty($two)){ $two = 0; }
        if(!isset($three) || empty($three)){
            $three = 0;
            $m3_app = [];
            $m3_app['app_lan'] = 0;
            $m3_app['app_lon'] = 0;
        }else{

            $m3_app1 = Db::table('up_z_app')->where('app_id',$three)->find();
            $m3_app2 = Db::table('up_z_app')->where('app_id',$three2)->find();
            $three = $three . ',' . $three2;
            $m3_app_param = [
                [$m3_app1['app_lan'],$m3_app1['app_lon']],
                [$m3_app2['app_lan'],$m3_app2['app_lon']]
            ];
            $lat_lon = $this->GetCenterFromDegrees($m3_app_param);
            $m3_app['app_lan'] = $lat_lon[0];
            $m3_app['app_lon'] = $lat_lon[1];
        }
        if(!isset($four) || empty($four)){
            $four = 0;
            $m4_app = [];
            $m4_app['app_lan'] = 0;
            $m4_app['app_lon'] = 0;
        }else{

            $m4_app1 = Db::table('up_z_app')->where('app_id',$four)->find();
            $m4_app2 = Db::table('up_z_app')->where('app_id',$four2)->find();
            $four = $four . ',' . $four2;
            $m4_app_param = [
                [$m4_app1['app_lan'],$m4_app1['app_lon']],
                [$m4_app2['app_lan'],$m4_app2['app_lon']]
            ];
            $lat_lon = $this->GetCenterFromDegrees($m4_app_param);
            $m4_app['app_lan'] = $lat_lon[0];
            $m4_app['app_lon'] = $lat_lon[1];
        }
        $m_name = Db::table('up_match')->where('match_id',$m_id)->value('match_title');
        $g_name = Db::table('up_match_group')->where('mg_id',$g_id)->value('mg_name');

        $msi_name = Db::table('up_match_sail_image')->where('msi_id',$msi_id)->value('msi_image');
        $sf_name = Db::table('up_setsail_flag')->where('sf_id',$sf_id)->value('sf_image');
        $fs_name = Db::table('up_flag_signal')->where('fs_id',$fs_id)->value('fs_image');

        $start_app1 = Db::table('up_z_app')->where('app_id',$start)->find();
        $start_app2 = Db::table('up_z_app')->where('app_id',$start2)->find();
        $start = $start . ',' . $start2;
        $start_app_param = [
            [$start_app1['app_lan'],$start_app1['app_lon']],
            [$start_app2['app_lan'],$start_app2['app_lon']]
        ];
        $lat_lon = $this->GetCenterFromDegrees($start_app_param);
        $start_app['app_lan'] = $lat_lon[0];
        $start_app['app_lon'] = $lat_lon[1];

        $m1_app = Db::table('up_z_app')->where('app_id',$one)->find();
        $m2_app = Db::table('up_z_app')->where('app_id',$two)->find();
//        $m3_app = Db::table('up_z_app')->where('app_id',$three)->find();
//        $m4_app = Db::table('up_z_app')->where('app_id',$four)->find();
        $end_app1 = Db::table('up_z_app')->where('app_id',$end)->find();
        $end_app2 = Db::table('up_z_app')->where('app_id',$end2)->find();
        $end = $end . ',' . $end2;
        $end_app_param = [
            [$end_app1['app_lan'],$end_app1['app_lon']],
            [$end_app2['app_lan'],$end_app2['app_lon']]
        ];
        $lat_lon = $this->GetCenterFromDegrees($end_app_param);
        $end_app['app_lan'] = $lat_lon[0];
        $end_app['app_lon'] = $lat_lon[1];

        $data = array();
        $data['mn_user_id'] = $user_id;
        $data['mn_m_id'] = $m_id;
        $data['mn_m_name'] = $m_name;
        $data['mn_g_id'] = $g_id;
        $data['mn_g_name'] = $g_name;
        $data['mn_l_id'] = $l_id;
        $data['mn_msi_id'] = $msi_id;
        $data['mn_msi_name'] = $msi_name;
        $data['mn_sf_id'] = $sf_id;
        $data['mn_sf_name'] = $sf_name;
        $data['mn_fs_id'] = $fs_id;
        $data['mn_fs_name'] = $fs_name;
        $data['mn_weilan'] = $weilan;
        $data['mn_begin_time'] = $time;
        $data['mn_start_appid'] = $start;
        $data['mn_start_lat'] = $start_app['app_lan'];
        $data['mn_start_lon'] = $start_app['app_lon'];
        $data['mn_one_appid'] = $one;
        $data['mn_lat_1'] = $m1_app['app_lan'];
        $data['mn_lon_1'] = $m1_app['app_lon'];
        $data['mn_two_appid'] = $two;
        $data['mn_lat_2'] = $m2_app['app_lan'];
        $data['mn_lon_2'] = $m2_app['app_lon'];
        $data['mn_three_appid'] = $three;
        $data['mn_lat_3'] = $m3_app['app_lan'];
        $data['mn_lon_3'] = $m3_app['app_lon'];
        $data['mn_four_appid'] = $four;
        $data['mn_lat_4'] = $m4_app['app_lan'];
        $data['mn_lon_4'] = $m4_app['app_lon'];
        $data['mn_end_appid'] = $end;
        $data['mn_lat_end'] = $end_app['app_lan'];
        $data['mn_lon_end'] = $end_app['app_lon'];
        Db::table('up_match_now')->insert($data);
        return  json(array('status'=>200,'msg'=>'ok'));
    }
    /**
     * 开始比赛之前选图了
     * 参数：
     * $m_id，$g_id，$l_id，$msi_id，$sf_id，$fs_id
     * $start，$one，$two，$three，$four，$end
     * @return string
     */
    public function choosePics(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $msi_name = Db::table('up_match_sail_image')->where('msi_id',$msi_id)->value('msi_image');
        $sf_name = Db::table('up_setsail_flag')->where('sf_id',$sf_id)->value('sf_image');
        $fs_name = Db::table('up_flag_signal')->where('fs_id',$fs_id)->value('fs_image');
        $g_name = Db::table('up_match_group')->where('mg_id',$g_id)->value('mg_name');
        $data = array();
        $data['mn_m_id'] = $m_id;
        $data['mn_msi_name'] = $msi_name;
        $data['mn_msi_id'] = $msi_id;
        $data['mn_sf_name'] = $sf_name;
        $data['mn_sf_id'] = $sf_id;
        $data['mn_fs_name'] = $fs_name;
        $data['mn_fs_id'] = $fs_id;
        $data['mn_g_id'] = $g_id;
        $data['mn_g_name'] = $g_name;
        $data['mn_l_id'] = $l_id;
        $data['mn_weilan'] = $weilan;
        $data['mn_begin_time'] = $time;
        $have = Db::table('up_match_choose')->where('mn_m_id',$m_id)->find();
        if($have){
            $res=Db::table('up_match_choose')->where('mn_m_id',$m_id)->update($data);
        }else{
            $res=Db::table('up_match_choose')->insert($data);
        }
        if($res){
            return  json(array('status'=>200,'msg'=>'ok'));
        }else{
            return  json(array('status'=>100,'msg'=>'切换失败，请重试！'));
        }

    }
    /**
     * 开始比赛之前选图了
     * 参数：
     * $m_id，$g_id，$l_id，$msi_id，$sf_id，$fs_id
     * $start，$one，$two，$three，$four，$end
     * @return string
     */
    public function getTypePics(){
        extract(input());
        if($type == 1){
            $res = Db::table('up_match_sail_image')
                ->where('msi_status',1)
                ->select();
            foreach ($res as $k=>$v){
                $temp = [];
                $v['msi_biao_name'] = explode('-',$v['msi_biao_name']);
                foreach ($v['msi_biao_name']  as $key=>$value){
                    if(strlen($value)>2){
                        $value = explode('/',$value);
                        if(count($value)<2){
                            $value = explode('&',$value);
                        }
                        $temp = array_merge($temp,$value);
                    }else{
                         array_push($temp,$value);
                    }

                }
                $res[$k]['msi_biao_name'] = implode('-',$temp);
            }
        }elseif ($type == 2){
            $res = Db::table('up_setsail_flag')
                ->where('sf_status',1)
                ->select();
        }elseif ($type == 3){
            $res = Db::table('up_flag_signal')
                ->where('fs_status',1)
                ->select();
        }else{
            return  json(array('status'=>0,'msg'=>'传参错误'));
        }

        return  json(array('status'=>200,'msg'=>$res));

    }
    /**
     * 看看有没有在进行中的比赛，用户进来或者裁判进来：TODO：周洋有没有告诉这个人是裁判吗？
     * 结束某个轮次的比赛也是调这个
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function inMatch(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $match = Db::table('up_match_now')
            ->where('mn_m_id',$m_id)
            ->where('mn_end_time','2000-12-12 12:12:12')
            ->find();
        if(empty($match)){
            $have = Db::table('up_match_choose')->where('mn_m_id',$m_id)->find();
            if($have){
                $match = $have;
            }else{
                $match = [];
            }
        }
        return  json_encode(array('status'=>200,'msg'=>$match));
    }
    /**
     * 结束某个轮次的比赛：TODO：看看要不要分开
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function endMatch(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $match = Db::table('up_match_now')
            ->where('mn_m_id',$m_id)
            ->where('mn_end_time','2000-12-12 12:12:12')
            ->find();
        if(empty($match)){
            $match = [];
        }else{
            //如果还有没有比赛完的，先加进去，并且是最后一名
            $subQuery = Db::table('up_match_datas')
                ->where('mm_match_id',$m_id)
                ->where('mm_mg_id',$match['mn_g_id'])
                ->where('mm_ml_id',$match['mn_l_id'])
                ->order('mm_time desc')
                ->buildSql();
            $reldata = Db::table($subQuery."a")
                ->group('mm_user_id')
                ->order('mm_time desc')
                ->select();
            $have = Db::table('up_match_ls_res')
                ->where('ls_m_id',$m_id)
                ->where('ls_mg_id',$match['mn_g_id'])
                ->where('ls_ml_id',$match['mn_l_id'])
                ->order('ls_time asc')
                ->column('ls_user_id');
            if(count($have) < count($reldata)){
                $insertres = [];
                foreach ($reldata as $k=>$v){
                    if(!in_array($v['mm_user_id'],$have)){
                        $insertres[] = [
                            'ls_m_id' => $m_id ,
                            'ls_mg_id' => $match['mn_g_id'] ,
                            'ls_ml_id' => $match['mn_l_id'] ,
                            'ls_user_id' => $v['mm_user_id'] ,
                            'ls_score' => count($reldata) ,
                            'ls_time' => $time
                        ];
                    }
                }
                $next = Db::table('up_match_ls_res')->insertAll($insertres);
                if(!$next){
                    return  json_encode(array('status'=>100,'msg'=>'失效船只未入库，请刷新重试'));
                }
            }
            $res = Db::table('up_match_now')
                ->where('mn_id',$match['mn_id'])
                ->setField('mn_end_time',$time);
            if($res){
                return  json_encode(array('status'=>200,'msg'=>'ok'));
            }else{
                return  json_encode(array('status'=>100,'msg'=>'请刷新重试'));
            }
        }
        return  json_encode(array('status'=>200,'msg'=>$match));
    }
    /**
     * 进来之后我来给你返回数据(教练或者用户)
     */
    public function getDatas(){
        extract(input());
        $time = date('Y-m-d H:i:s');
        $match = Db::table('up_match_now')
            ->where('mn_m_id',$m_id)
            ->where('mn_end_time','2000-12-12 12:12:12')
            ->find();
        if(!isset($starttime) || $starttime == ''){
            $starttime = $time;
        }
        if(!isset($endtime) || $endtime == ''){
            $endtime = $time;
        }
        $down_list = [];
        $reldata = [];
        if($match){
            //先给所有船员的数据：
            $subQuery = Db::table('up_match_datas')
                ->where('mm_match_id',$m_id)
                ->where('mm_mg_id',$match['mn_g_id'])
                ->where('mm_ml_id',$match['mn_l_id'])
                ->whereTime('mm_time','between',[$starttime,$endtime])
                ->order('mm_time desc')
                ->buildSql();
            $reldata = Db::table($subQuery."a")
//                    ->field("a.mm_lat,a.mm_lon,a.mm_user_id,a.mm_match_id,a.mm_mg_id,a.mm_ml_id")
                ->group('mm_user_id')
                ->order('mm_time desc')
                ->select();
            $chaminutes = strtotime($time) - strtotime($match['mn_begin_time']);
            $cha = $chaminutes / 60;//是不是超过5分钟了
            $match['minutes'] = 300 - $chaminutes;
            if($chaminutes >= 300){
                $match['minutes'] = $chaminutes - 300;
            }
            if($cha > 5){ //只有你在里面在比赛了，而且超过5分钟了，说明你有数据了，就可以计算了
                $have = Db::table('up_match_ls_res')
                    ->where('ls_m_id',$m_id)
                    ->where('ls_mg_id',$match['mn_g_id'])
                    ->where('ls_ml_id',$match['mn_l_id'])
                    ->order('ls_time asc')
                    ->column('ls_user_id');
//                if(count($have) < count($reldata)){ //结算成绩的数量要小于参加比赛的队伍的数量
                    $scores = [];
                    $havedatas = [];
                    foreach ($reldata as $k=>$v){
                        if(!in_array($v['mm_user_id'],$have)){
                            $distance = $this->getDistance($v['mm_lat'],$v['mm_lon'],$match['mn_lat_' . $v['mm_biao']],$match['mn_lon_' . $v['mm_biao']]);
                            $v['distance'] = $distance;
                            $scores[] = $v;
                        }else{
                            $v['distance'] = 0;
                            $v['upone'] = 0;
                            $havedatas[] = $v;
                        }

                    }
//                        先按照距离正序排，再按照等级倒序排
                    if($scores){
                        $scores = arrayToSort($scores,'distance',"SORT_ASC");
                        $scores = arrayToSort($scores,'mm_times',"SORT_DESC");
                        foreach ($scores as $k => $v){
                            if($k > 0){
                                $scores[$k]['upone'] = $v['distance'] - $scores[$k-1]['distance'];
                            }else{
                                $scores[$k]['upone'] = 0;
                            }
                        }
                    }
                    $down_list = array_merge($havedatas,$scores);
//                }
            }
        }else{
            $have = Db::table('up_match_choose')->where('mn_m_id',$m_id)->find();
            if($have){
                $match = $have;
            }else{
                $match = [];
            }
            $match['minutes'] = 0;
            //如果没有在开始的比赛，我就把所有的都给你
            $subQuery = Db::table('up_match_datas')
                ->where('mm_match_id',$m_id)
                ->whereTime('mm_time','between',[$starttime,$endtime])
                ->order('mm_time desc')
                ->buildSql();
            $reldata = Db::table($subQuery."a")
//                    ->field("a.mm_user_id,a.mm_lon,a.mm_user_id,a.mm_match_id,a.mm_mg_id,a.mm_ml_id")
                ->group('mm_user_id')
                ->order('mm_time desc')
                ->select();
            if($reldata){
                foreach ($reldata as $kk => $vv){
                    $reldata[$kk]['subs'] =  Db::table('up_match_datas')
                        ->where('mm_match_id',$m_id)
                        ->where('mm_user_id',$vv['mm_user_id'])
                        ->whereTime('mm_time','between',[$starttime,$endtime])
                        ->field('mm_lat,mm_lon')
                        ->order('mm_time asc')
                        ->select();
                }
            }
        }
        return  json(array('status'=>200,'msg'=>$match,'reldata'=>$reldata,'down_list'=>$down_list,'time'=>$time));
    }

    /**
     * 临时成绩/最终成绩
     */
    public function getResult()
    {
        extract(input());
        $field = 'ls_m_id,ls_user_id,sum(ls_score) scores';
        $nows = Db::table('up_match_ls_res')
            ->where('ls_m_id',$m_id)
            ->where('ls_mg_id',$g_id)
            ->group('ls_user_id')
            ->order('scores asc')
            ->field($field)
            ->select();
        if($nows){
            $lc = Db::table('up_match_ls_res')
                ->where('ls_m_id',$m_id)
                ->where('ls_mg_id',$g_id)
                ->group('ls_ml_id')
                ->order('ls_ml_id desc')
                ->value('ls_ml_id');
            $prevs = Db::table('up_match_ls_res')
                ->where('ls_m_id',$m_id)
                ->where('ls_mg_id',$g_id)
                ->where('ls_ml_id','<>',$lc)
                ->group('ls_user_id')
                ->order('scores asc')
                ->field($field)
                ->select();
            foreach ($nows as $k => $v){
                $two = Db::table('up_match_apply_info')
                    ->where('ma_match_id',$m_id)
                    ->where('ma_apply_status',2)
                    ->where('ma_user_id',$v['ls_user_id'])
                    ->field('ma_fan_code,ma_user_name')
                    ->find();
                $nows[$k]['top'] = $k + 1;
                $nows[$k]['fan_num'] = $two['ma_fan_code'];
                $nows[$k]['captain_name'] = $two['ma_user_name'];
                $nows[$k]['level_up'] = 0;
                if($prevs){
                    $found_key = array_search($v['ls_user_id'], array_column($prevs, 'ls_user_id'));
                    $nows[$k]['level_up'] = $found_key - $k;
                }
            }
        }
        return  json(array('status'=>200,'msg'=>$nows));
    }
    protected function getDistance($lat1, $lng1, $lat2, $lng2){
        // 将角度转为狐度
        $radLat1 = deg2rad($lat1);// deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2)+cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378137;
        return $s;

    }
    //---------------------------------设备端绑定--------------------------
    public function shebeiBind()
    {
        extract(input());
        $shebei = Db::table('up_z_app')
            ->where('app_sb_id',$sb_id)
            ->find();
        if(!$shebei){
            $number = rand(1000,9999);
            $num = $this->getNumber($number);
            $ercode = $this->scerweima($number);
            $data = [
                'app_sb_id' => $sb_id,
                'app_id' => $num,
                'app_number' => $num,
                'app_ercode' => $ercode,
                'app_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_z_app')->insert($data);
            if($res){
                $shebei = Db::table('up_z_app')->where('app_sb_id',$sb_id)->find();
                return  json(array('status'=>200,'msg'=>$shebei));
            }else{
                return  json(array('status'=>100,'msg'=>'绑定失败，请刷新重试！'));
            }
        }
        return  json(array('status'=>200,'msg'=>$shebei));
    }
    public function getNumber($number)
    {
        extract(input());
        $shebei = Db::table('up_z_app')
            ->where('app_number',$number)
            ->find();
        if($shebei){
            $num = rand(1000,9999);
            return $this->getNumber($num);
        }else{
            return $number;
        }
    }
    public function scerweima($aid){
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        require_once VENDOR_PATH . "phpqrcode.php";
        $rand = date('YmdHis').rand(100000,999999);
        $value = "$aid"; //二维码内容：链接
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 8;           //生成图片大小
        //生成二维码图片
        $ymd = date('Ymd');
        $zip_path = "{$dir}/uploads/face/$ymd";
        if (!file_exists($zip_path)) {
            mkdir($zip_path);
        }
        $filename = "$zip_path/{$rand}.png";
        $filehttp = "{$url}/uploads/face/$ymd/{$rand}.png";
        \QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = $filename;              //已经生成的原始二维码图片文件
        $QR = imagecreatefromstring(file_get_contents($QR));
        //输出图片
//        imagepng($QR, 'qrcode.png');
        imagedestroy($QR);
        return $filehttp;
    }
    public function shebeiSet()
    {
        extract(input());
        $data = [
            'app_fx' => '',
            'app_fs' => '',
            'app_lx' => '',
            'app_ls' => '',
            'app_lan' => $lat,
            'app_lon' => $lon,
        ];
        $shebei = Db::table('up_z_app')
            ->where('app_number',$number)
            ->update($data);
        return  json(array('status'=>200,'msg'=>'ok'));
    }
    public function GetCenterFromDegrees($data){

        if (!is_array($data)) return FALSE;

        $num_coords = count($data);

        $X = 0.0;
        $Y = 0.0;
        $Z = 0.0;

        foreach ($data as $coord){

            $lat = deg2rad((float)$coord[0]);
            $lon = deg2rad((float)$coord[1]);

            $a = cos($lat) * cos($lon);
            $b = cos($lat) * sin($lon);
            $c = sin($lat);

            $X += $a;
            $Y += $b;
            $Z += $c;
        }

        $X /= $num_coords;
        $Y /= $num_coords;
        $Z /= $num_coords;

        $lon = atan2($Y, $X);
        $hyp = sqrt($X * $X + $Y * $Y);
        $lat = atan2($Z, $hyp);

        return array(rad2deg($lat), rad2deg($lon));
    }
    public function mww(){
        $a = [
            [116.203911,40.025706],[116.206282,40.026341]
        ];
        $b = $this->GetCenterFromDegrees($a);
        dump($b);die;
        $userdb = array(
            0 => array(
                'uid' => 100,
                'name' => 'Sandra Shush',
                'url' => 'urlof100'
            ),

            1 => array(
                'uid' => 5465,
                'name' => 'Stefanie Mcmohn',
                'pic_square' => 'urlof100'
            ),

            2 => Array(
                'uid' => 40489,
                'name' => 'Michael',
                'pic_square' => 'urlof40489'
            )
        );

        $found_key = array_search(40489, array_column($userdb, 'uid'));
        var_dump($found_key);

    }

}